import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import './index.less';
import { Carousel, Card, List, WhiteSpace, ListView, Toast, NavBar, Modal } from "antd-mobile";
import { Row, Icon, Button, Col } from "antd";
import { request, setMainFormBack } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
// import { Activity } from "src/projects/models/activity";
import { getAppPermissonObject, ROUTE_PATH } from "src/projects/app/util-tool";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
import { getGoodLookTimeShow } from "./index";
// import moment from "moment";
// const Item = List.Item;
// const Brief = Item.Brief;
var QRCode = require('qrcode.react');
/**
 * 组件：活动详情视图控件状态
 */
const prompt = Modal.prompt;
export interface ActivityDetailViewState extends ReactViewState {
    /** 数据 */
    data?: any;
    /** 图片高度 */
    imgHeight?: number | string;
    /** 评论列表 */
    comment_list?: any[];
    /** 长列表数据 */
    dataSource?: any;
    // 评论内容
    comment_content?: string;
    // user信息
    user?: any;
    // 是否收藏
    is_collection?: boolean;
    // 二维码是否显示
    qrcodeModalStatus?: boolean;
    // popup是否显示
    popupModalStatus?: boolean;
    // 家人档案信息
    family_data?: any;
    // 是否能审核
    isAudit?: boolean;
    // 是否已发送
    is_send?: boolean;
}
/**
 * 组件：活动详情视图控件
 */
export class ActivityDetailView extends ReactView<ActivityDetailViewControl, ActivityDetailViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            data: {},
            comment_list: [],
            imgHeight: 176,
            dataSource: ds,
            comment_content: '',
            user: [],
            is_collection: false,
            qrcodeModalStatus: false,
            popupModalStatus: false,
            family_data: false,
            isAudit: false,
            is_send: false,
        };
    }
    componentDidMount() {
        // let param = {};
        this.setState({
            user: IntelligentElderlyCareAppStorage.getCurrentUser(),
        });
        let id = this.props.match!.params.key;
        request(this, AppServiceUtility.activity_service.get_activity_list!({ 'all': true, 'id': id }))
            .then((data: any) => {
                if (data.result.length > 0) {

                    let stateData = {
                        data: data.result[0],
                        is_collection: data.result[0]['collection_data'] ? true : false,
                    };

                    if (this.props.location!.state && this.props.location!.state.hasOwnProperty('select_family_data')) {
                        stateData['family_data'] = this.props.location!.state.select_family_data;
                    }
                    this.setState(
                        stateData,
                        () => {
                            if (this.props.location!.state && this.props.location!.state.hasOwnProperty('select_family_data')) {
                                this.showModal('popupModalStatus');
                            }
                        }
                    );
                }
            });
        request(this, AppServiceUtility.person_org_manage_service.check_permission!({ 'method': 'audit', 'type': 'activity' }))
            .then((data: any) => {
                if (data.code === 'Success') {
                    this.setState({
                        isAudit: data.isAudit,
                    });
                }
            });
        // this.getCommentList();
    }
    getCommentList() {
        let id = this.props.match!.params.key;
        AppServiceUtility.comment_service.get_comment_list_all!({ 'comment_object_id': id })!
            .then((data: any) => {
                let comment_list: any[] = [];
                if (data) {
                    comment_list = data.result.map((key: any, value: any) => {
                        let comment = {};
                        comment['id'] = key['id'];
                        comment['content'] = key['content'];
                        comment['comment_date'] = key['comment_date'];
                        comment['like_list'] = key.like_list;
                        comment['comment_user'] = key['comment_user'];
                        return comment;
                    });
                    this.setState(
                        { comment_list }
                    );
                }
            });
    }
    /** 参与活动 */
    on_click() {
        const family_data = this.state.family_data;
        if (family_data === false) {
            this.familyChoose();
            return;
        }
        this.showModal('popupModalStatus');
    }
    /** 取消参与 */
    on_cancel_click() {
        let data = this.state.data;
        if (!data || !data['id']) {
            Toast.info('活动加载中...');
            return;
        }
        request(this, AppServiceUtility.activity_service.cancel_participate_activity!(data['id']))
            .then((data: any) => {
                if (data === 'Success') {
                    Toast.success('取消成功', 3, () => {
                        window.location.reload();
                    });
                    // this.props.history!.push(ROUTE_PATH.activityList);
                } else {
                    Toast.fail(data);
                }
            });
    }

    onClickRow = (id: string) => {
        this.props.history!.push(ROUTE_PATH.childCommmentList + '/' + id);
    }

    // 签到
    onSignin() {
        this.props.history!.push(ROUTE_PATH.activitySignIn + '/' + this.state.data['id']);
    }
    // 不做任何事情
    notDo() {
    }

    private btn_row = (id: string, type: string | undefined, amount: string, data: any) => {
        if (this.state.isAudit === true && data['step_no'] !== undefined && data['step_no'] !== -1 && data['status'] !== undefined && data['status'] !== '不通过') {
            return (
                <List className="confirmation-orders-buttom info-list">
                    <Button className="btnW950" type="primary" onClick={() => this.auditOpen()}>审核</Button>
                </List>
            );
        }
        if (data.hasOwnProperty('step_no') && data['step_no'] !== -1 && data['step_no'] !== '-1') {
            return (
                <List className="confirmation-orders-buttom info-list">
                    <Button className="btnW950" onClick={() => this.notDo()}>待审批</Button>
                </List>
            );
        }
        switch (type) {
            case '已报名未开始':
                return (
                    <List className="confirmation-orders-buttom info-list">
                        <Button className="btnW950" type='primary' onClick={() => this.on_cancel_click()}>取消报名</Button>
                    </List>
                );
            case '已报名进行中':
                if (data.hasOwnProperty('is_participate') && data['is_participate'] === 1) {
                    return (
                        <List className="confirmation-orders-buttom info-list">
                            <Button className="btnW950" type='primary' onClick={() => this.notDo()}>已签到</Button>
                        </List>
                    );
                } else {
                    return (
                        <List className="confirmation-orders-buttom info-list">
                            <Button className="btnW950" type='primary' onClick={() => this.onSignin()}>签到</Button>
                        </List>
                    );
                }
            case '已报名已结束':
                return (
                    <List className="confirmation-orders-buttom info-list">
                        <Button className="btnW950" onClick={() => this.notDo()}>活动已结束</Button>
                    </List>
                );
            case '未报名未开始':
                return (
                    <List className="confirmation-orders-buttom info-list">
                        <Button className="btnW950" type='primary' onClick={() => this.on_click()}>点击报名</Button>
                    </List>
                );
            case '未报名已开始':
                return (
                    <List className="confirmation-orders-buttom info-list">
                        <Button className="btnW950" onClick={() => this.notDo()}>活动进行中</Button>
                    </List>
                );
            case '未报名已结束':
                return (
                    <List className="confirmation-orders-buttom info-list">
                        <Button className="btnW950" onClick={() => this.notDo()}>活动已结束</Button>
                    </List>
                );
            default:
                return null;
        }
    }
    setContent(e: any) {
        this.setState({
            comment_content: e,
        });
    }
    sendComment(id: any) {
        if (!this.state.comment_content) {
            Toast.fail('请输入评论内容！');
            return false;
        }
        let param: any = {
            type_id: '42ec6dd2-c002-11e9-a315-f45fc101cb0b',
            comment_object_id: this.props.match!.params.key,
            content: this.state.comment_content,
        };
        let that = this;
        request(this, AppServiceUtility.comment_service.update_comment!(param))
            .then((data: any) => {
                that.getCommentList();
            });
        return false;
    }
    getTag(isColor: boolean = false) {
        const data = this.state.data;
        const begin_date_time = new Date(data['begin_date']).getTime();
        const end_date_time = new Date(data['end_date']).getTime();
        const now_date_time = new Date().getTime();
        const spanWidth = 4;
        const style = {
            borderRadius: '5px',
            color: '#fff',
            padding: '2px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        };
        if (data.hasOwnProperty('step_no') && data['step_no'] !== -1 && data['step_no'] !== '-1') {
            if (isColor) {
                return '#595959';
            }
            return (
                <Col span={spanWidth} style={{ background: "#595959", ...style }}>待审批</Col>
            );
        }
        if (now_date_time > end_date_time) {
            if (isColor) {
                return '#595959';
            }
            return (
                <Col span={spanWidth} style={{ background: "#595959", ...style }}>已结束</Col>
            );
        } else if (now_date_time <= end_date_time && now_date_time >= begin_date_time) {
            if (isColor) {
                return '#5b9bd5';
            }
            return (
                <Col span={spanWidth} style={{ background: "#5b9bd5", ...style }}>进行中</Col>
            );
        } else if (data['participate_count'] >= data['max_quantity']) {
            if (isColor) {
                return '#ffc000';
            }
            return (
                <Col span={spanWidth} style={{ background: "#ffc000", ...style }}>已满员</Col>
            );
        } else if (now_date_time < begin_date_time) {
            if (isColor) {
                return '#ed7d31';
            }
            return (
                <Col span={spanWidth} style={{ background: "#ed7d31", ...style }}>报名中</Col>
            );
        } else {
            if (isColor) {
                return '#000000';
            }
            return (
                <Col span={7} />
            );
        }
    }
    toCollection(type: string, id: string) {
        let data: any = this.state.data;
        if (!data || !data['id']) {
            Toast.info('活动加载中...');
            return;
        }
        if (type === 'add') {
            request(this, AppServiceUtility.service_follow_collection_service.update_service_follow_collection!(id, 'collection', '活动'))
                .then((datas: any) => {
                    if (datas === 'Success') {
                        data['collection_count'] = data['collection_count'] + 1;
                        this.setState(
                            {
                                data,
                                is_collection: true,
                            },
                            () => {
                                Toast.success('收藏成功');
                            }
                        );
                    }
                }).catch((error: Error) => {
                    console.error(error.message);
                });
        } else if (type === 'del') {
            request(this, AppServiceUtility.service_follow_collection_service.delete_service_follow_collection_by_business_id!({ busindess: id, type: 'collection', object: '活动' }))
                .then((datas: any) => {
                    if (datas === 'Success') {
                        data['collection_count'] = data['collection_count'] - 1;
                        if (data['collection_count'] < 0) {
                            data['collection_count'] = 0;
                        }
                        this.setState(
                            {
                                data,
                                is_collection: false,
                            },
                            () => {
                                Toast.success('取消收藏成功');
                            }
                        );
                    }
                }).catch((error: Error) => {
                    console.error(error.message);
                });
        }
    }
    showModal(keys: any) {
        this.setState({
            [keys]: true,
        });
    }
    hideModal(keys: any) {
        this.setState({
            [keys]: false,
        });
    }
    activityParticipate() {
        let { data, family_data } = this.state;
        if (!data || !data['id']) {
            Toast.info('活动加载中...');
            return;
        }
        let family_ids = [];
        for (let i in family_data) {
            if (family_data[i]) {
                family_ids.push(family_data[i]['id']);
            }
        }
        request(this, AppServiceUtility.activity_service.participate_activity!({ id: data['id'], family_ids }))
            .then((data: any) => {
                if (data === 'Success') {
                    this.props.history!.push(ROUTE_PATH.activityParticipate + '/Success');
                } else {
                    Toast.fail(data);
                    // this.props.history!.push(ROUTE_PATH.activityParticipate + '/Fail');
                }
            });
    }
    familyChoose() {
        const activity_info = this.state.data;
        this.props.history!.push(ROUTE_PATH.familyList, {
            url: ROUTE_PATH.activityDetail,
            key: activity_info['id'],
        });
        return;
    }
    auditOpen() {
        prompt('资讯审核', '', [
            {
                text: '不通过',
                onPress: value => {
                    this.auditThis('不通过', value);
                },
            },
            {
                text: '通过',
                onPress: value => {
                    this.auditThis('通过', value);
                },
            }]);
    }
    auditThis(type: string, value: string = '') {
        let { data } = this.state;
        if (type === '不通过' && value === '') {
            Toast.info('不通过请填写原因！');
            return;
        }
        let param: any = {
            // 审批标识
            'is_sp': 1,
            // 审批状态
            'sp_status': type,
            // 主数据状态
            'status': type,
            // 审批信息
            'sp_msg': value,
            // 步骤
            'step_no': 2,
            // 主键ID
            'id': data['id'],
        };
        const is_send = this.state.is_send;
        const that = this;
        // 正在发送请求
        if (is_send === true) {
            Toast.fail('请勿操作过快！');
            return;
        }
        this.setState(
            {
                is_send: true,
            },
            () => {
                request(that, AppServiceUtility.activity_service.update_activity!(param))
                    .then((data: any) => {
                        if (data === 'Success') {
                            Toast.success('操作成功！', 3, () => history.back());
                        } else {
                            Toast.fail(data);
                        }
                    }).catch((error: Error) => {
                        Toast.fail(error.message);
                    });
            }
        );
        return;
    }
    render() {
        // let { data } = this.state;
        let id = this.props.match!.params.key;
        let { data, user, is_collection, qrcodeModalStatus, popupModalStatus, family_data, } = this.state;
        const AppPermission = JSON.parse(localStorage.getItem(LOCAL_FUNCTION_LIST)!);
        // let id = this.props.match!.params.key;
        // let type = this.props.match!.params.code;
        // const comment = (owData: any, sectionID: any, rowID: any) => {
        //     return (
        //         <div>
        //             <Card>
        //                 <Row type='flex' justify='center' onClick={this.onClickRow.bind(this, owData.id)}>
        //                     <Col className='list-col' span={3}><WhiteSpace size='sm' /><Avatar size='large' icon="user" /></Col>
        //                     <Col span={20} className='list-col'>
        //                         <WhiteSpace size='sm' />
        //                         <Row>
        //                             <Col span={12}><strong>{owData.comment_user}</strong></Col>
        //                             <Col span={12}>{moment(owData.comment_date).format("YYYY-MM-DD hh:mm")}</Col>
        //                         </Row>
        //                         <Row>
        //                             {owData.content}
        //                         </Row>
        //                     </Col>
        //                 </Row>
        //             </Card>
        //         </div>
        //     );
        // };

        // 百度地图url
        let lat = data.hasOwnProperty('organization_lat') || '';
        let lon = data.hasOwnProperty('organization_lon') || '';
        let map_url = "http://api.map.baidu.com/marker?location=" + lat + "," + lon + "&title=" + data.organization_name + "&output=html";
        setMainFormBack('.ny-news-info svg', () => {
            this.props.history!.push(ROUTE_PATH.activityList);
        });
        return (
            <div>
                <NavBar
                    className={data && data['activity_name'] && data['activity_name'].length > 11 ? "ny-news-info start" : "ny-news-info"}
                    icon={<Icon type={"left"} />}
                    rightContent={(user && user['id'] && data && data['apply_user_id'] && user['id'] === data['apply_user_id']) || AppPermission && getAppPermissonObject(AppPermission, '活动列表', '编辑') ? <Row type="flex" justify="end" onClick={() => this.props.history!.push(ROUTE_PATH.changeActivity + '/' + this.props.match!.params.key)}>编辑</Row> : null}
                >
                    {
                        data && data['activity_name'] ? data['activity_name'] : ''
                    }
                </NavBar>
                <Carousel
                    autoplay={true}
                    infinite={true}
                >
                    {data!.photo ? data!.photo!.map((val: any) => (
                        <a
                            className='carousel-a'
                            key={val}
                            href="javascript:;"
                            style={{ height: this.state.imgHeight }}
                        >
                            <img
                                className='carousel-img'
                                src={val}
                                alt=""
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                    this.setState({ imgHeight: 'auto' });
                                }}
                            />
                        </a>
                    )) :
                        <a
                            className='carousel-a'
                            key={1}
                            href="javascript:;"
                            style={{ height: this.state.imgHeight }}
                        >
                            <img
                                className='carousel-img'
                                src={'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1564975937&di=cac390b27275e6a039d3a1eeb2b338bf&src=http://img.mp.itc.cn/upload/20170816/ede70cf3a497447fa423391b154fe7b0_th.jpg'}
                                alt=""
                                onLoad={() => {
                                    window.dispatchEvent(new Event('resize'));
                                    this.setState({ imgHeight: 'auto' });
                                }}
                            />
                        </a>}
                </Carousel>
                <Card className='info-card'>
                    <Row>
                        <Col span={20}><strong>{data.activity_name}</strong></Col>
                        {this.getTag()}
                    </Row>

                    <WhiteSpace size="md" />
                    <Row type="flex" justify="end">
                        <Col span={18}>
                            <Row>
                                {data.organization_name}
                            </Row>
                            <Row>
                                {/* {data.organization_address} */}
                                {data.address}
                            </Row>
                            <Row type="flex" justify="space-between">
                                <Col>联系人：{data.contacts}</Col>
                                <Col><a href={`tel:${data.phone}`}>{data.phone}</a></Col>
                                <Col><a href={map_url} target="_blank"><Icon className='item-icon-size' type="compass" /></a></Col>
                            </Row>
                        </Col>
                        <Col span={6}>
                            <Row type="flex" justify="end">
                                <QRCode onClick={() => this.showModal('qrcodeModalStatus')} value={window.location.origin + ROUTE_PATH.activitySignIn + '/' + data['id']} size={50} fgColor={this.getTag(true)} />
                            </Row>
                        </Col>
                    </Row>
                    <WhiteSpace size="lg" />
                    <Row>{getGoodLookTimeShow(data.begin_date, data.end_date)}</Row>
                    <WhiteSpace size="sm" />
                    <Row>
                        <Col span={10} className="font-orange">{data.amount === '0' || data.amount === 0 ? '免费' : (data.amount !== undefined ? `￥${data.amount}` : '')}</Col>
                        <Col span={10}>已报名 {data.participate_count || 0}/{data.max_quantity}</Col>
                        {is_collection === true ? <Col span={4} onClick={() => this.toCollection('del', data['id'])}><Icon className='item-icon-size font-red' type="star" theme="filled" />{data.collection_count || 0}</Col> : <Col span={4} onClick={() => this.toCollection('add', data['id'])}><Icon className='item-icon-size' type="star" />{data.collection_count || 0}</Col>}
                    </Row>
                </Card>
                <Card>
                    <Card.Header
                        title="活动介绍"
                    />
                    <Card.Body>
                        {data.introduce && data.introduce.length > 0 ? <div dangerouslySetInnerHTML={{ __html: data.introduce! }} /> : '暂无介绍'}
                    </Card.Body>
                </Card>
                <WhiteSpace size="sm" />
                {/* <Card className='list-conten'>
                    <Card.Header
                        title="评论"
                    />
                    <div className='tabs-content'> */}
                {/* {
                            comment_list && comment_list.length ?
                                <ListView
                                    ref={el => this['lv'] = el}
                                    dataSource={dataSource.cloneWithRows(comment_list)}
                                    renderRow={comment}
                                    initialListSize={10}
                                    pageSize={10}
                                // renderBodyComponent={() => <MyBody />}
                                // style={{ height: this.state.height }}
                                />
                                :
                                <Row className='tabs-content' type='flex' justify='center'>
                                    暂无评论
                                </Row>

                        } */}
                {/* {(() => {
                            if (comment_list && comment_list.length) {
                                return comment_list.map((item: any, index: number) => {
                                    return (
                                        <List key={index} className="my-list">
                                            <Item extra={item.content}>{item.comment_user}</Item>
                                        </List>);
                                });
                            }
                            return (
                                <Row className='tabs-content' type='flex' justify='center'>
                                    无评论
                                </Row>
                            );
                        })()} */}
                {/* </div>
                </Card> */}
                {/* <WhiteSpace size="sm" />
                {(() => {
                    if (data.per_status === '已报名进行中') {
                        return (
                            <Card>
                                <List renderHeader={() => '发表评论'}>
                                    <InputItem clear={true} placeholder="请输入评论内容" onChange={(e) => this.setContent(e)} />
                                </List>
                                <Row type="flex" justify="end">
                                    <Button type='primary' onClick={() => this.sendComment(id)}>发布评论</Button>
                                </Row>
                            </Card>
                        );
                    }
                    return null;
                })()} */}
                <WhiteSpace size="sm" />
                <WhiteSpace size="sm" />
                <WhiteSpace size="sm" />
                <WhiteSpace size="sm" />
                {
                    this.btn_row(id, data.per_status, data.amount === '0' || !data.amount ? '免费' : data.amount, data)
                }
                {/* <List className="confirmation-orders-buttom info-list">
                    <Item extra={<Button type='primary'>立即参与</Button>}>
                        <Row type='flex' justify='center'>¥500</Row>
                    </Item>
                </List> */}
                <Modal
                    visible={qrcodeModalStatus!}
                    transparent={true}
                    maskClosable={true}
                    footer={[{ text: '关闭', onPress: () => { this.hideModal('qrcodeModalStatus'); } }]}
                >
                    <QRCode value={window.location.origin + ROUTE_PATH.activitySignIn + '/' + data['id']} size={200} fgColor={this.getTag(true)} />
                </Modal>
                {family_data && family_data.length > 0 ? <Modal
                    className="defaultModal"
                    popup={true}
                    visible={popupModalStatus!}
                    onClose={() => { this.hideModal('popupModalStatus'); }}
                    animationType="slide-up"
                >
                    <List renderHeader={() => <div>已选家人</div>} className="popup-list">
                        {family_data.map((item: any, index: number) => (
                            <List.Item key={index}>
                                <Row>
                                    <Col span={18}>
                                        {item.hasOwnProperty('family_person') && item['family_person'].length > 0 && item['family_person'][0].hasOwnProperty('name') ? item['family_person'][0]['name'] : ''}
                                    </Col>
                                    <Col span={6}>
                                        {item.hasOwnProperty('relation_type_name') && item['relation_type_name'] ? item['relation_type_name'] : ''}
                                    </Col>
                                </Row>
                            </List.Item>
                        ))}
                        <List.Item>
                            <Button className="btnW950" type="primary" onClick={() => this.familyChoose()}>重新选择</Button>
                        </List.Item>
                        <List.Item>
                            <Button className="btnW950" type="primary" onClick={() => this.activityParticipate()}>确定报名</Button>
                        </List.Item>
                    </List>
                </Modal> : null}
            </div >
        );
    }
}

/**
 * 组件：活动详情视图控件
 * 控制活动详情视图控件
 */
@addon('ActivityDetailView', '活动详情视图控件', '控制活动详情视图控件')
@reactControl(ActivityDetailView, true)
export class ActivityDetailViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}